﻿using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Y2.Filters
{
    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        ///// <summary>
        ///// 验证入口
        ///// </summary>
        ///// <param name="filterContext"></param>
        //public override void OnAuthorization(AuthorizationContext filterContext)
        //{
        //    base.OnAuthorization(filterContext);
        //}
        ///// <summary>
        ///// 验证核心代码
        ///// </summary>
        ///// <param name="httpContext"></param>
        ///// <returns></returns>
        //protected override bool AuthorizeCore(HttpContextBase httpContext)
        //{
        //    //前端请求api时会将token存放在名为"auth"的请求头中
        //    var authHeader = httpContext.Request.Headers["Authorization"];
        //    if (authHeader == null)
        //    {
        //        httpContext.Response.StatusCode = 401;
        //        return false;
        //    }
        //    users userInfo = null;
        //    //根据token反序列化对象
        //    try
        //    {
        //        userInfo = JWTHelper.GetJwtDecode(authHeader);
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        if (ex.Message == "Token has expired.")//令牌过期
        //        {
        //            httpContext.Response.StatusCode = 402;
        //            return false;
        //        }
        //        else if (ex.Message == "Invalid signature") //无效的签名
        //        {
        //            httpContext.Response.StatusCode = 403;
        //            return false;

        //        }

        //    }
        //    return true;
        //}
        ///// <summary>
        ///// 验证失败处理
        ///// </summary>
        ///// <param name="filterContext"></param>
        //protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        //{
        //    base.HandleUnauthorizedRequest(filterContext);
        //    if (filterContext.HttpContext.Response.StatusCode == 403)
        //    {
        //        filterContext.HttpContext.Response.Write("token被篡改");
        //    }
        //    else if (filterContext.HttpContext.Response.StatusCode == 401)
        //    {
        //        filterContext.HttpContext.Response.Write("token不存在");
        //    }
        //    else if (filterContext.HttpContext.Response.StatusCode == 402)
        //    {
        //        filterContext.HttpContext.Response.Write("token失效");
        //    }
        //}
    }
}
